package com.cassiopae.services;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cassiopae.dao.UserDaoImpl;
import com.cassiopae.entity.User;
/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDaoImpl daoImpl = new UserDaoImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		User user = new User();
		
		String email = request.getParameter("email");
		String pwd = request.getParameter("password");
		
		String[] schemaListSelected = request.getParameterValues("ToLB");
		
		List<String> schemaUser = new ArrayList<String>();
		
		schemaUser.addAll( Arrays.asList(schemaListSelected) );
		
		user.setEmail(email);
		user.init(email);
		user.setPwd(pwd);
		
		if ( daoImpl.create(user) ) { 
			if( schemaUser.size() > 0){
				daoImpl.addSchemasToUser(user, schemaUser);
			}
			user = (User) request.getSession().getAttribute("user");
			List<User> users = daoImpl.getAllWithoutLogin(user.getEmail());
			request.setAttribute("LISTUSER", users);
			getServletContext().getRequestDispatcher("/listUser.jsp").forward(request, response);
		}

	}
}
